<template>
  <div class="app-container">
    <el-card shadow="never" style="margin-top: 15px">
      <!-- 操作栏 -->
      <div class="operate-container">
        <div class="operate-button-container">
          <el-button type="primary" size="mini" @click="handleSave">保存</el-button>
        </div>
      </div>
      <!-- 店铺信息 -->
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266" />
        <span class="font-small">客户信息</span>
      </div>
      <div class="table-layout">
        <el-row>
          <el-col :span="5" class="table-cell-title">客户编码</el-col>
          <el-col :span="4" class="table-cell-title">客户名称</el-col>
          <el-col :span="5" class="table-cell-title">所属贸易商</el-col>
          <el-col :span="5" class="table-cell-title">供应商</el-col>
          <el-col :span="5" class="table-cell-title">备注</el-col>
        </el-row>
        <el-row>
          <el-col :span="5" class="table-cell required">
            <el-input v-model="storeFormData.storeCode" style="width: 90%;" placeholder="请输入客户买家编码" @change="handleCheckStoreCode"/>
          </el-col>
          <el-col :span="4" class="table-cell required">
            <el-input v-model="storeFormData.storeName" style="width: 90%;" placeholder="请输入客户买家名称"  />
          </el-col>
          <el-col :span="5" class="table-cell">
            <el-select v-model="storeFormData.mallId" style="width: 100%" clearable placeholder="请选择贸易商编号">
              <el-option v-for="option in options.mallIdOptions" :key="option.id" :label="option.customerName" :value="option.id" />
            </el-select>
          </el-col>
          <el-col :span="5" class="table-cell">
            <el-select v-model="storeFormData.supplierId" style="width: 100%" clearable placeholder="请选择供应商编号">
              <el-option v-for="option in options.supplierIdOptions" :key="option.id" :label="option.supplierName" :value="option.id" />
            </el-select>
          </el-col>
          <el-col :span="5" class="table-cell">
            <el-input v-model="storeFormData.remark" placeholder="请输入备注" />
          </el-col>
        </el-row>
      </div>
      <!-- 品牌信息 -->
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266" />
        <span class="font-small">品牌信息</span>
      </div>
      <div class="table-layout">
        <el-row :gutter="10" style="padding-top: 2px">
          <el-col :span="1.5" style="float: right;">
            <el-col :span="1.5" style="float: right;">
              <el-button style="float: right;" type="primary" icon="el-icon-plus" size="mini" @click="openBrandSelector">添加品牌</el-button>
              <brand-selector :visible.sync="brandSelectorVisible" @selected="handleSelectedBrand" />
            </el-col>
            <!--<el-button style="float: right;" type="primary" icon="el-icon-plus" size="mini" @click="handleAddBrand">添加品牌</el-button>-->
          </el-col>
        </el-row>
        <el-table ref="itemTable" :data="brandList" style="width: 100%;margin-top: 10px" border>
          <el-table-column label="品牌编码" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.brandCode" size="small" placeholder="请输入品牌编码" disabled />
            </template>
          </el-table-column>
          <el-table-column label="品牌名称" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.brandName" size="small" placeholder="请输入品牌名称" disabled />
            </template>
         </el-table-column>
          <el-table-column label="品牌授权号" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.authNo" size="small" placeholder="请输入品牌授权号" clearable />
            </template>
          </el-table-column>
          <el-table-column label="授权有效始" align="center">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.authStartDate" type="date" value-format="yyyy-MM-dd" size="small" style="width: 200px" placeholder="选择授权有效始" clearable />
            </template>
          </el-table-column>
          <el-table-column label="授权有效至" align="center">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.authExpDate" type="date" value-format="yyyy-MM-dd" size="small" style="width: 200px" placeholder="选择授权有效至" clearable />
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveBrand(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 商品信息 -->
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266" />
        <span class="font-small">商品信息</span>
      </div>
      <div class="table-layout">
         <el-row :gutter="10" style="padding-top: 2px">
          <el-col :span="1.5" style="float: left;">
            <el-input v-model="goodsQueryParams.goodsName" size="small" placeholder="请输入商品名称" clearable @keyup.enter.native="handleGoodsQuery" />
          </el-col>
          <el-col :span="1.5" style="float: left;">
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleGoodsQuery">搜索</el-button>
          </el-col>
          <el-col :span="1.5" style="float: right;">
            <el-button style="float: right;" type="primary" icon="el-icon-plus" size="mini" @click="handleGoodsAdd">添加商品</el-button>
          </el-col>
        </el-row>
        <el-table ref="itemTable" :data="goodsList" style="width: 100%;margin-top: 20px" border>
          <el-table-column label="商品" align="center">
            <template slot-scope="scope">
              <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['sku-Selector'].reset()">
                <sku-selector ref="sku-Selector" @selected="handleSelectedSku($event, scope.row)" />
                <el-input slot="reference" v-model="scope.row.skuName" placeholder="点击选择商品" readonly />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center">
             <template slot-scope="scope">
               <el-input v-model="scope.row.skuName" size="small" placeholder="请输入商品名称" clearable  />
             </template>
          </el-table-column>
          <el-table-column label="货号" align="center">
            <template slot-scope="scope">
             <el-input v-model="scope.row.sn" size="small" placeholder="请输入品牌名称" clearable />
            </template>
          </el-table-column>
          <el-table-column label="品牌名称" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.brandName" size="small" placeholder="请输入品牌名称" clearable />
            </template>
         </el-table-column>
         <el-table-column label="规格" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.spec" size="small" placeholder="请输入规格" clearable  />
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveGoods(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
      </div>
    </el-card>
  </div>
</template>

<script>
import StoreApi from '@/api/basic/StoreApi'
import CustomerApi from '@/api/basic/CustomerApi'
import SupplierApi from '@/api/basic/SupplierApi'
import SkuApi from '@/api/pms/SkuApi'
import BrandSelector from '@/views/goods/brand/BrandSelector'
import SkuSelector from '@/views/goods/sku/SkuSelector2.vue'

const defaultStoreFormData = {
  storeName: null,
  storeCode: null,
  mallId: null,
  supplierId: null,
  mallName: null,
  supplierName: null,
  goodsList: [],
  brandList: []
}
export default {
  name: 'StoreList',
  components: {
    BrandSelector,
    SkuSelector
  },
  data() {
    return {
      options: {
        mallIdOptions: [], // 商城编号字典
        supplierIdOptions: [], // 供应商编号字典
        sysYnTypeOptions: this.$constant.sysYnTypeOptions
      },
      goodsQueryParams: {
        goodsName: null,
        isValid: this.$constant.Y
      },
      goodsPage: {
        current: 1,
        pageSize: 10,
        total: 0,
        records: []
      },
      storeId: null,
      storeFormData: Object.assign({}, defaultStoreFormData),
      storeFormRules: {
      },
      brandList: [],
      goodsList: [],
      goodsLoading: false,
      isSingle: true,
      isMultiple: true,
      brandSelectorVisible: false
    }
  },
  created() {
    this.storeId = this.$route.params.id
    this.init()
    this.handleGoodsQuery()
    this.loadOptions()
  },
  methods: {
    init() {
      if (this.storeId) {
        StoreApi.get(this.storeId).then(response => {
          this.storeFormData = response.data
          // 加载品牌授权集合
          if (this.storeFormData.brandList) {
            this.brandList = this.storeFormData.brandList
          }
          if (this.storeFormData.goodsList) {
            this.goodsList = this.storeFormData.goodsList
          }
        })
      }
    },
    loadOptions() {
      CustomerApi.list().then(response => {
        this.options.mallIdOptions = response.data
      })
      SupplierApi.list().then(response => {
        this.options.supplierIdOptions = response.data
      })
    },
    handleSave() {
      if (this.storeFormData.storeCode) {
        if (this.storeFormData.storeCode.length > 20) {
          this.$message.error('店铺编码不能超过20个字符')
          return false
        }
      } else {
        this.$message.error('店铺编码不能为空')
        return false
      }
      if (!this.storeFormData.storeName) {
        this.$message.error('店铺名称不能为空')
        return false
      }
      // 保存品牌授权集合
      this.storeFormData.brandList = [...this.brandList]
      this.storeFormData.goodsList = [...this.goodsList]
      if (this.storeFormData.id) {
        StoreApi.edit(this.storeFormData).then(response => {
          this.$message.success('修改成功')
          this.$router.push('/basic/store')
        })
      } else {
        StoreApi.add(this.storeFormData).then(response => {
          this.$message.success('添加成功')
          this.$router.push('/basic/store')
        })
      }
    },
    // handleGoodsAdd() {
    //   this.$router.push('/spu/form/')
    // },
    handleGoodsEdit(row) {
      this.$router.push({ path: '/spu/form/' + row.id })
    },
    handleGoodsQuery() {
      if (this.storeId) {
        this.goodsLoading = true
        this.goodsQueryParams.storeId = this.storeId
        SkuApi.page(this.goodsQueryParams, this.goodsPage).then(response => {
          this.goodsPage.records = response.data.records
          this.goodsPage.total = response.data.total
          this.goodsLoading = false
        }, () => {
          this.goodsLoading = false
        })
      }
    },
    openBrandSelector() {
      this.brandSelectorVisible = true
    },
    handleSelectedBrand(brands) {
      if (brands && brands.length > 0) {
        for (let i = 0; i < brands.length; i++) {
          const brand = brands[i]
          let isExisted = false
          // 校验品牌是否重复
          for (let j = 0; j < this.brandList.length; j++) {
            const brandFromList = this.brandList[j]
            if (brand.id === brandFromList.brandId) {
              this.$message.warning("品牌【" + brand.brandName + '】已添加')
              isExisted = true
              break
            }
          }
          if (!isExisted) {
            this.brandList.push({
              brandId: brand.id,
              brandCode: brand.brandCode,
              brandName: brand.brandName,
              letter: brand.letter,
              logo: brand.logo,
              authExpDate: null, // 授权过期时间
              authNo: null, // 授权号
              authStartDate: null // 授权开始时间
            })
          }
        }
      }
    },
    handleSelectedSku(obj, row) {
      row.skuId = obj.id
      row.skuName = obj.skuName
      row.sn = obj.sn
      row.brandName = obj.brandName
      row.spec = obj.spec
    },
    handleGoodsAdd() {
      this.goodsList.push({
        skuId: null,
        skuName: null,
        brandName: null,
        sn: null,
        spec: null
      })
    },
    handleAddBrand() {
      this.brandList.push({
        brandId: null,
        brandCode: null,
        authExpDate: null, // 授权过期时间
        authNo: null, // 授权号
        authStartDate: null, // 授权开始时间
        brandName: null,
        letter: null,
        logo: null
      })
    },
    handleRemoveGoods(row) {
      this.goodsList.splice(this.goodsList.indexOf(row), 1)
    },
    handleRemoveBrand(row) {
      this.brandList.splice(this.brandList.indexOf(row), 1)
    },
    handleCheckStoreCode() {
      const params = {
        id: this.storeFormData.id,
        storeCode: this.storeFormData.storeCode
      }
      StoreApi.checkStoreCode(params).then(response => {
        if (!response.data) {
          this.$message.error('店铺编码重复')
        }
      })
    }
  }
}
</script>
<style scoped>
  .app-container {
    width: 80%;
    margin: 20px auto;
  }

  .detail-container {
    width: 80%;
    padding: 20px 20px 20px 20px;
    margin: 20px auto;
  }

  .operate-container {
    background: #F2F6FC;
    height: 80px;
    margin: -20px -20px 0;
    line-height: 80px;
  }

  .operate-button-container {
    float: right;
    margin-right: 20px
  }

  .table-layout {
    margin-top: 20px;
    border-left: 1px solid #DCDFE6;
    border-top: 1px solid #DCDFE6;
  }

  .table-cell {
    height: 60px;
    line-height: 40px;
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
    font-size: 14px;
    color: #606266;
    text-align: center;
    overflow: hidden;
  }

  .table-cell-title {
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
    background: #F2F6FC;
    text-align: center;
    font-size: 14px;
    color: #303133;
  }
</style>
